package cn.daniellee.plugin.rb.listener;

import cn.daniellee.plugin.rb.ResidenceBungee;
import cn.daniellee.plugin.rb.core.BungeeCore;
import com.bekvon.bukkit.residence.Residence;
import com.bekvon.bukkit.residence.api.ResidenceApi;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class PlayerListener implements Listener {

	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent e) {
		// 在首个玩家进服时获取服务器名称
		if (!BungeeCore.fetchedName) {
			new BukkitRunnable() {
				@Override
				public void run() {
					BungeeCore.fetchServerName(e.getPlayer());
				}
			}.runTaskLater(ResidenceBungee.getInstance(), 1);
		}
		// 检查待传送信息，如果有，将其传送到目标领地
		Player player = e.getPlayer();
		String targetResidence = BungeeCore.teleportMap.get(player.getName());
		if (targetResidence != null) {
			BungeeCore.teleportMap.remove(player.getName());
			// 延迟一个Tick后传送
			new BukkitRunnable() {
				@Override
				public void run() {
					Residence.getInstance().getResidenceManager().getByName(targetResidence).tpToResidence(player, player, false);
				}
			}.runTaskLater(ResidenceBungee.getInstance(), 1);
		}
	}

	@EventHandler
	public void onPlayerChat(PlayerCommandPreprocessEvent e) {
		// 拦截领地相关指令
		if (e.getMessage().startsWith("/residence ") || e.getMessage().startsWith("/res ") || e.getMessage().startsWith("/resadmin ")) {
			String[] args = e.getMessage().split(" ");
			if (args.length > 1) {
				switch (args[1].toLowerCase()) {
					case "tp":
						// 查询目标领地，如果不存在，查询领地Map，如果在其他服务器，传送玩家到目标服务器
						if (args.length == 3 && Residence.getInstance().getResidenceManager().getByName(args[2]) == null) {
							String targetServer = BungeeCore.residenceMap.get(args[2]);
							if (targetServer != null) {
								// 取消该事件
								e.setCancelled(true);
								// 向目标服务器发送消息
								ByteArrayDataOutput out = ByteStreams.newDataOutput();
								out.writeUTF("Forward");
								out.writeUTF(targetServer);
								out.writeUTF("ResidenceBungee");
								ByteArrayOutputStream msgBytes = new ByteArrayOutputStream();
								DataOutputStream msgOut = new DataOutputStream(msgBytes);
								try {
									msgOut.writeUTF("Teleport");
									msgOut.writeUTF(e.getPlayer().getName());
									msgOut.writeUTF(args[2]);
								} catch (IOException ignored) { }
								out.writeShort(msgBytes.toByteArray().length);
								out.write(msgBytes.toByteArray());
								e.getPlayer().sendPluginMessage(ResidenceBungee.getInstance(), "BungeeCord", out.toByteArray());
								// 将玩家传送到目标服务器
								out = ByteStreams.newDataOutput();
								out.writeUTF("Connect");
								out.writeUTF(targetServer);
								e.getPlayer().sendPluginMessage(ResidenceBungee.getInstance(), "BungeeCord", out.toByteArray());
							}
						}
						break;
					case "set":
						if (args.length < 4 || !("tp".equalsIgnoreCase(args[2]) && "tp".equalsIgnoreCase(args[3]))) {
							break;
						}
					case "create":
					case "remove":
						// 一秒后发送领地列表
						new BukkitRunnable() {
							@Override
							public void run() {
								BungeeCore.sendResListMessage("ALL");
							}
						}.runTaskLater(ResidenceBungee.getInstance(), 20);
						break;
				}
			}
		}
	}

}
